<template>
	<div class="system-user-container">
		<el-card class="box-card">
			<div>
				<div class="my_btn_lay">
					<div class="my_flex my_btn" @click="searchEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--search"></i>
							<span>查找</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="resetEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--refresh"></i>
							<span>重置</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="addDefaultBlank">
						<div class="my_flex_layout">
							<i class="vxe-icon--plus"></i>
							<span>新增</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="deleteTable">
						<div class="my_flex_layout">
							<i class="fa fa-trash-o"></i>
							<span>删除</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="uploadingbutton">
						<div class="my_flex_layout">
							<i class="vxe-icon--upload"></i>
							<span>导入</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="funnelEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--download"></i>
							<span>导出</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="printTab">
						<div class="my_flex_layout">
							<i class="vxe-icon--print"></i>
							<span>打印</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="showAmendFun">
						<div class="my_flex_layout">
							<i class="el-icon-edit"></i>
							<span>编辑</span>
						</div>
					</div>
					<div class="my_flex my_btn ml20" @click="editClosedEvent">
						<div class="my_flex_layout">
							<i class="el-icon-folder-add"></i>
							<span>保存</span>
						</div>
					</div>
				</div>

				<vxe-form :data="selectFrom" title-align="left" prevent-submit title-colon>
					<vxe-form-item title="单位名称" field="tiunitNameme" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.tiunitNameme" placeholder="请选择单位名称">
								<el-option v-for="item in selectFrom.unitsData" :key="item.unitName" :label="item.unitName" :value="item.unitName"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<vxe-form-item title="开始时间" field="time" span="5" :item-render="{}">
						<template #default="{ data }">
							<el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="data.time1" type="date" placeholder="开始时间"> </el-date-picker>
						</template>
					</vxe-form-item>

					<vxe-form-item title="结束时间" field="time" span="5" :item-render="{}">
						<template #default="{ data }">
							<el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="data.time2" type="date" placeholder="结束日期"> </el-date-picker>
						</template>
					</vxe-form-item>
					<vxe-form-item title="联系人" field="contactPerson" span="4" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.contactPerson" placeholder="请选择联系人">
								<el-option v-for="item in selectFrom.unitsData" :key="item.id" :label="item.contactPerson" :value="item.contactPerson"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>
					<vxe-form-item title="单位类型" field="type" span="4" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.type" placeholder="请选择单位类型">
								<el-option v-for="item in selectFrom.typeArry" :key="item.value" :label="item.label" :value="item.value"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<!-- <vxe-form-item align="right" span="24" collapse-node>
						<template #default>
							<vxe-button status="primary" content="搜索" @click="searchEvent"></vxe-button>
							<vxe-button content="重置" @click="resetEvent"></vxe-button>
						</template>
					</vxe-form-item> -->
				</vxe-form>
			</div>

			<!-- <vxe-toolbar ref="xToolbar" custom>
				<template #buttons>
					<vxe-button type="text" icon="fa fa-plus" content="新增" @click="addDefaultBlank"></vxe-button>
					<vxe-button type="text" icon="fa fa-trash-o" content="删除" @click="deleteTable"></vxe-button>
				</template>
				<template #tools>
					<vxe-button type="text" icon="vxe-icon--print" class="tool-btn" @click="printTab"></vxe-button>
					<vxe-button type="text" icon="vxe-icon--download" class="tool-btn" @click="funnelEvent"></vxe-button>
				</template>
			</vxe-toolbar> -->
			<!-- @edit-closed="editClosedEvent" -->
			<vxe-table
				border
				align="center"
				keep-source
				ref="xTable1"
				:scroll-x="{ enabled: false }"
				:scroll-y="{ enabled: false }"
				:export-config="{}"
				height="780"
				resizable
				show-overflow
				class="mytable-style"
				:row-class-name="rowClassName"
				:data="tableData"
				:edit-rules="validRules"
				:edit-config="{ trigger: 'manual', mode: 'row',icon: 'false'  }"
				@checkbox-all="selectAllChangeEvent1"
				@checkbox-change="selectChangeEvent1"
			>
				<vxe-column align="center" fixed="left" type="checkbox" width="60"></vxe-column>
				<vxe-column align="center" type="seq" title="序号" width="60"></vxe-column>

				<vxe-column field="unitName" title="单位名称" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>

				<!-- <vxe-column field="borrowerId" title="单位名称" :edit-render="{ type: 'default' }">
					<template v-slot:edit="scope">
						<el-select filterable v-model="scope.row.borrowerId">
							<el-option v-for="item in selectFrom.unitsData" :key="item.id" :label="item.contactPerson" :value="item.id"></el-option>
						</el-select>
					</template>
					<template v-slot="{ row }">{{ getSelectLabel(row.borrowerId, selectFrom.unitsData) }}</template>
				</vxe-column> -->

				<vxe-column field="taxpayerNum" title="纳税人识别号" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column field="addressPhone" title="注册地址" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<!-- <vxe-column field="accountBank" title="开户行" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column> -->
				<!-- <vxe-column field="bankAccount" title="开户行账号" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column> -->

				<!-- <vxe-column field="accountBank" title="开户行及账号" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column> -->

				<vxe-column field="contactPerson" title="联系人" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column field="phone1" title="联系电话1" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column field="phone2" title="联系电话2" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column field="qq" title="QQ号" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column field="addr" title="联系地址" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column width="100" field="type" title="单位类型" :edit-render="{ name: '$select', options: selectFrom.typeArry }"></vxe-column>
			</vxe-table>
		</el-card>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, ref, toRaw, onMounted, nextTick } from 'vue';

import { ElMessage, ElMessageBox } from 'element-plus';
import { axios_SelList, axios_addressBook } from '/@/api/basicsUrl/index'; //通讯录接口
import { axios_contactsAdd, axios_contactsdel, axios_contactsup } from '/@/api/addressBook/index';
// 不重复id
import { GenNonDuplicateID } from '/@/utils/formatTime';
import { axios_excelcontacts } from '/@/api/basicsUrl/index'; //通过单位查询项目
import { VXETable, VxeTableInstance, VxeTableEvents, VxeTablePropTypes } from 'vxe-table';

export default {
	name: 'PaymentDetail',
	setup() {
		const xTable1 = ref({} as VxeTableInstance);
		const xToolbar = ref({} as VxeToolbarInstance);

		const validRules = ref({
			unitName: [{ required: true, message: '单位名称必选' }],
			taxpayerNum: [{ required: true, message: '纳税人识别号必填' }],
			contactPerson: [{ required: true, message: '联系人必选' }],
			type: [{ required: true, message: '单位类型必选' }],
		} as VxeTablePropTypes.EditRules);

		// 打印样式
		// 打印样式
		const printStyle = `
            .title {
              text-align: center;
            }
            .my-list-row {
              display: inline-block;
              width: 100%;
            }
            .my-list-col {
              float: left;
              width: 33.33%;
              height: 28px;
              line-height: 28px;
            }
            .my-top,
            .my-bottom {
              font-size: 12px;
            }
            .my-top {
              margin-bottom: 5px;
            }
            .my-bottom {
              margin-top: 30px;
              text-align: right;
            }
            `;

		// 打印顶部内容模板
		const topHtml = `
            <h1 class="title">出货单据</h1>
            <div class="my-top">
              <div class="my-list-row">
                <div class="my-list-col">商品名称： </div>
                <div class="my-list-col">发货单号：X2665847132654</div>
                <div class="my-list-col">发货日期：2020-09-20</div>
              </div>
              <div class="my-list-row">
                <div class="my-list-col">收货姓名： </div>
                <div class="my-list-col">收货地址：火星第七区18号001</div>
                <div class="my-list-col">联系电话：10086</div>
              </div>
            </div>
            `;

		// 打印底部内容模板
		const bottomHtml = `
            <div class="my-bottom">
              <div class="my-list-row">
                <div class="my-list-col"></div>
                <div class="my-list-col">创建人： </div>
                <div class="my-list-col">创建日期：2020-09-20</div>
              </div>
            </div>
            `;

		/**
		 * @Author: lilin_:）
		 * @name: 默认空白数组
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		let defaultBlankData = [
			{
				iswebAdd: true,
				webid: GenNonDuplicateID(),
				unitName: '',
				taxpayerNum: '',
				addressPhone: '',
				accountBank: '',
				bankAccount: '',
				bankName: '',
				contactPerson: '',
				phone1: '',
				phone2: '',
				qq: '',
				addr: '',
				type: 2,
			},
		];

		const state: any = reactive({
			addList: [], //前端加的数据
			responseData: [], //后端返回的数据
			selectFrom: {
				tiunitNameme: '', //单位名称
				contactPerson: '', //联系人
				type: '', //单位类型1供应商2客户3公司员工
				time1: '', //开始时间
				time2: '', //结束时间
				on: 0, //进来默认on=0,点击=1，保存刷新=2

				typeArry: [
					{ label: '供应商', value: '1' },
					{ label: '客户', value: '2' },
					{ label: '公司员工', value: '3' },
					{ label: '合作伙伴', value: '4' },
				], //单位类型1供应商2客户3公司员工
				unitsData: [], //单位搜索的数据和联系人一样
			},
			tableData: [], //表格数据
			selectData: [], //选择的数组
		});

		const selectAllChangeEvent1: VxeTableEvents.CheckboxAll = ({ checked, records }: any) => {
			console.log(checked ? '所有勾选事件' : '所有取消事件', records);
			state.selectData = records;
		};

		const selectChangeEvent1: VxeTableEvents.CheckboxChange = ({ checked, records }: any) => {
			// 重置所有高亮
			state.tableData.forEach((item2: any) => {
				item2.hghligHt = false;
			});
			state.selectData = records;
			console.log(checked ? '勾选事件' : '取消事件', records);
			state.selectData.forEach((item: any) => {
				if (item.iswebAdd) {
					// 前端的数据
					state.tableData.forEach((item2: any) => {
						if (item.webid == item2.webid) {
							item2.hghligHt = true;
						}
					});
				} else {
					state.tableData.forEach((item2: any) => {
						if (item.id == item2.id) {
							item2.hghligHt = true;
						}
					});
				}
			});
		};

		/**
		 * @Author: lilin_:）
		 * @name: 获取项目名称
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const getProjectName = async () => {
			let resData: any = await axios_addressBook({
				unitName: state.selectFrom.tiunitNameme,
				contactPerson: state.selectFrom.contactPerson,
				type: state.selectFrom.type,
				time1: state.selectFrom.time1, //开始时间
				time2: state.selectFrom.time2, //结束
				on: state.selectFrom.on, //进来默认on=0,点击=1，保存刷新=2
			});

			if (resData.code == 200) {
				// 重置数据
				state.addList = [];
				// 添加20条数据
				for (let index = 0; index < 20; index++) {
					state.addList.push(
						defaultBlankData.map((item: any) => {
							return {
								...item,
								...{
									webid: GenNonDuplicateID(),
								},
							};
						})[0]
					);
				}
				// 存储数组索引
				state.responseData = resData.obj;
				state.tableData = [...state.responseData, ...state.addList];
				state.selectData = [];
			}
		};

		//获取通讯录数
		const getSelectressBook = async () => {
			let resData: any = await axios_SelList({ unitName: '', contactPerson: '', type: '' });
			state.selectFrom.unitsData = resData.obj;
			// state.tableData = resData.obj;
			// data1 = resData.obj;
			console.log(toRaw(resData.obj), '我是单位名称');
		};

		const searchEvent: VxeFormEvents.Submit = async () => {
			// VXETable.modal.message({ content: '查询事件', status: 'info' });
			state.selectFrom.on = 1; //进来默认on=0,点击=1，保存刷新=2
			await getProjectName();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 重置搜索表单
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const resetEvent: VxeFormEvents.Reset = async () => {
			state.selectFrom.on = 0; //重置传0
			state.selectFrom.tiunitNameme = ''; //清空时间
			state.selectFrom.contactPerson = ''; //单位名称
			state.selectFrom.type = ''; //项目名称
			await getProjectName();
			// VXETable.modal.message({ content: '重置事件', status: 'info' });
		};

		onMounted(() => {
			getProjectName(); //列表
			getSelectressBook(); //获取搜索数据域
			// let a = GenNonDuplicateID()
			// console.log(a)
		});

		//实时更新
		const editClosedEvent: VxeTableEvents.EditClosed = ({ row, column }) => {
			// let getRow: any = row;

			if (state.selectData.length == 1) {
				let row = state.selectData[0];
				if (row.iswebAdd) {
					// 走保存接口
					// console.log(toRaw(row), '我是前端提交');
					axios_contactsAdd(row).then((res) => {
						// console.log(res, '是否啊添加');
						if (res.code == 200) {
							state.selectFrom.on = 2; //进来默认on=0,点击=1，保存刷新=2
							getProjectName(); //列表
							VXETable.modal.message({ content: '新增成功!', status: 'success' });
						}
					});
				} else {
					axios_contactsup(row).then((res) => {
						if (res.code == 200) {
							state.selectFrom.on = 1; //进来默认on=0,点击=1，保存刷新=2
							getProjectName(); //列表
							VXETable.modal.message({ content: '编辑成功！', status: 'success' });
						}
					}); // console.log(toRaw(row), '我是后段提交');
				}
			} else if (state.selectData.length == 0) {
				VXETable.modal.message({ content: '您还没有选中行', status: 'warning' });
			} else {
				VXETable.modal.message({ content: '只能选中一行编辑', status: 'warning' });
			}

			// const $table = xTable1.value;
			// const field = column.property;
			// const cellValue = row[field];
			// 判断单元格值是否被修改;
			// if ($table.isUpdateByRow(row, field)) {
			// 	setTimeout(() => {
			// 		VXETable.modal.message({
			// 			content: `局部保存成功！ ${field}=${cellValue}`,
			// 			status: 'success',
			// 		});
			// 		// 局部更新单元格为已保存状态
			// 		$table.reloadRow(row, null, field);
			// 	}, 300);
			// }
		};

		/**
		 * @Author: lilin_:）
		 * @name: 关联表格
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		nextTick(() => {
			// 将表格和工具栏进行关联
			// const $table = xTable1.value;
			// const $toolbar = xToolbar.value;
			// $table.connect($toolbar);
		});

		/**
		 * @Author: lilin_:）
		 * @name: 新增空白行
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const addDefaultBlank = () => {
			let addArry = defaultBlankData.map((item: any) => {
				return {
					...item,
					...{
						webid: GenNonDuplicateID(),
						hghligHt: true,
					},
				};
			});

			let row = addArry[0];
			// let showArry = JSON.parse(JSON.stringify(state.tableData)); // state.responseData.push(row);
			state.addList.unshift(row);
			// state.tableData = showArry;
			state.tableData = [...state.responseData, ...state.addList];
			// console.log(row, 'row');
			const $table = xTable1.value;
			$table.clearCheckboxRow();
			$table.toggleCheckboxRow(state.addList[0]); //默认选中第一行
			state.selectData = [state.addList[0]]; //拿到选择数据
			$table.setActiveRow(row);
			ElMessage.success({
				message: '新增1行空白栏',
				type: 'success',
			});
			// 计算滚动高度
			let heightpx = state.responseData.length * 48;
			setTimeout(() => {
				document.getElementsByClassName('vxe-table--body-wrapper')[0].scrollTo(0, heightpx);
			}, 100);
		};

		/**
		 * @Author: lilin_:）
		 * @name: 删除数据
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const deleteTable: any = async () => {
			let webAddArry: any = [];
			let reeData: any = [];
			state.selectData.forEach((item: any) => {
				if (item.iswebAdd == true) {
					webAddArry.push(item);
				} else {
					reeData.push(item);
				}
			});
			// 判断前端数据是否有值
			let webDelet = () => {
				if (webAddArry.length != 0) {
					// 前端删除
					state.addList = state.addList.filter((item: any) => {
						return !webAddArry.find((_item: any) => _item.webid === item.webid);
					});
					state.selectData = [];
					state.tableData = [...state.responseData, ...state.addList];
				}
			};

			let resDelet = async () => {
				if (reeData.length != 0) {
					let { code }: object = await axios_contactsdel(
						reeData.map((item: any) => {
							return item.id;
						})
					);
					// console.log(code, '11111111');
					if (code == 200) {
						state.selectFrom.on = 2; //进来默认on=0,点击=1，保存刷新=2

						getProjectName(); //列表();
					}
				}
			};
			await resDelet();
			await webDelet();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 高级导出功能
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const funnelEvent = () => {
			const $table = xTable1.value;
			$table.openExport();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 打印表格
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const printTab = () => {
			const $table = xTable1.value;
			$table.print({
				sheetName: '通讯录',
				style: printStyle, //自定义样式
				columns: [
					{ field: 'unitName' },
					{ field: 'taxpayerNum' },
					{ field: 'addressPhone' },
					{ field: 'accountBank' },
					{ field: 'bankAccount' },
					{ field: 'contactPerson' },
					{ field: 'phone1' },
					{ field: 'phone2' },
					{ field: 'qq' },
					{ field: 'addr' },
					{ field: 'type' },
				],
				beforePrintMethod: ({ content }) => {
					// 拦截打印之前，返回自定义的 html 内容
					// return topHtml + content + bottomHtml;
					return content;
				},
			});
		};

		// 展示内容下拉搜索
		const getSelectLabel = (value, list) => {
			let item = list.find((item) => item.id == value);
			return item ? item.contactPerson : null;
		};

		// 导入文件
		let uploadingbutton = async (item: any) => {
			console.log(toRaw(item), 'item');
			try {
				const { file } = await VXETable.readFile({
					multiple: true,
				}); // 数据表 1出纳表 2合同表 3商票台账
				// let params = {
				// 	dataSheet: 3,
				// 	id: item.id,
				// };
				console.log(file, 'file');
				let formData = new FormData();
				formData.append('file', file);
				axios_excelcontacts(formData).then((res: any) => {
					if (res.code == 200) {
						// state.selectFrom.on = 0; // //默认是0，1是点击
						state.selectFrom.on = 2; //进来默认on=0,点击=1，保存刷新=2
						getProjectName();
						VXETable.modal.alert(`共：1 个文件`);
					}
				}); // 开始处理数据
			} catch (e) {
				ElMessage.error({
					message: '上传出错啦',
					type: 'error',
				});
			}
		};
		// 编辑保存
		const showAmendFun = () => {
			if (state.selectData.length == 1) {
				let row = state.selectData[0];
				row.hghligHt = true;
				const $table = xTable1.value;
				$table.setActiveRow(row);
			} else if (state.selectData.length == 0) {
				VXETable.modal.message({ content: '您还没有选中行', status: 'warning' });
			} else {
				VXETable.modal.message({ content: '只能选中一行编辑', status: 'warning' });
			}
		};

		// 改变颜色样式
		const rowClassName: VxeTablePropTypes.RowClassName = ({ row }) => {
			// console.log(row, 'rowIndex');
			if (row.hghligHt) {
				return 'row-green';
			}
			return null;
		};

		return {
			validRules,
			showAmendFun, //编辑
			uploadingbutton, //导入文件
			...toRefs(state),
			editClosedEvent, //实时更新
			xToolbar, //关联表格
			xTable1, //表格
			addDefaultBlank, //新增空白行
			deleteTable, //删除数据
			funnelEvent, //导出数据
			printTab, //打印
			getSelectLabel, //回显下拉

			selectAllChangeEvent1,
			selectChangeEvent1,
			input: ref(''),
			searchEvent,
			resetEvent,
			rowClassName,
		};
	},
};
</script>

<style scoped lang="scss">
.mytable-style ::v-deep .vxe-body--row.row-green {
	background-color: #bbb;
	color: #fff;
}
</style>
